package com.ipan.okhttp.response.handle;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import com.ipan.kits.mapper.JsonMapper;

import okhttp3.Response;

/**
 * JSON处理器,将得到的JSON字符串转为JavaBean.
 *
 * @author iPan
 * @version 2019-12-25
 */
public class JsonDataHandler<T> implements DataHandler<T> {

	/**
	 * 指定类型
	 */
	private Class<T> delegateClass;

	public JsonDataHandler() {
	}

	public JsonDataHandler(Class<T> delegateClass) {
		this.delegateClass = delegateClass;
	}

	public Class<T> getDelegateClass() {
		return delegateClass;
	}

	public void setDelegateClass(Class<T> delegateClass) {
		this.delegateClass = delegateClass;
	}

	/**
	 * 得到相应结果后,将相应数据转为需要的数据格式
	 *
	 * @param response 需要转换的对象
	 * @return 转换结果
	 * @throws IOException 出现异常
	 */
	@Override
	public T handle(final Response response) throws IOException {
		StringDataHandler stringDataHandler = StringDataHandler.create();
		String valueContent = stringDataHandler.handle(response);
		if (StringUtils.isNotBlank(valueContent)) {
			if (null != this.delegateClass) {
				return JsonMapper.getDefaultJsonMapper().fromJson(valueContent, delegateClass);
			} else {
				return null;
			}
		}
		return null;
	}
}
